package com.tastyshop.admincontroller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.tastyshop.domain.Member;
import com.tastyshop.service.MemberService;

@Controller
public class AdminMemberController {
	
	@Autowired 
	private MemberService service;
		
	@RequestMapping(value = "admin.do", method = RequestMethod.GET)
	public String admin_main(){
		return "admin";
	}
	
	@RequestMapping(value = "member_manage.do")
	public String member_list(HttpServletRequest request ,Model model)throws Exception{
	
	    int page = 1;
		if(request.getParameter("page") != null){
			page = Integer.parseInt(request.getParameter("page"));
		}
		int rows = 10;
		
		String field="";
		if(request.getParameter("field") != null){
			field = request.getParameter("field");
		}
		
		String keyword="";
		if(request.getParameter("keyword") != null){
			keyword = request.getParameter("keyword");
		}
		
		if("".equals(keyword)){
			field = "";
		}
					
		List<Member> members = service.getMembersList(field, keyword, page, rows);
		
		int cnt = members.size();
		if(cnt == 0){
			return "redirect:member_manage.do";
		}
		String totCnt="";
		totCnt = members.get(0).getTOT_CNT();
		int viewCnt = 10;
		int totalCnt = Integer.parseInt(totCnt);
		int pageCnt = totalCnt/viewCnt+(totalCnt%viewCnt == 0 ? 0 : 1);
		int startPage = 1;
		if(page%10 != 0){
			startPage = (int)(page/10)*10+1;
		}else{
			startPage = ((int)(page/10)-1)*10+1;
		}
		int totalPage = (int)Math.ceil((totalCnt / (double)viewCnt));
		int pageBlock = 10;
		int endPage = startPage + pageBlock -1;
		if(endPage > pageCnt) endPage = pageCnt;
		
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("cnt", cnt);
		model.addAttribute("members", members);
		model.addAttribute("totCnt", totCnt);
		model.addAttribute("keyword", keyword);
		model.addAttribute("field", field);
		model.addAttribute("page", page);
		model.addAttribute("startPage",startPage);
		model.addAttribute("endPage",endPage);
		return "member_manage";
	}
}
